# _*_coding:utf-8_*_
"""
该文件用于对mongo 中的数据查询后同步到本地，mongo数据库，并修改远程mongo数据库中的字段


"""

import asyncio
import os
import sys

project_path = os.path.dirname(os.path.abspath("__file__"))
project_path_fa = os.path.dirname(project_path)
print(project_path)
print(project_path_fa)
sys.path.append(project_path)
sys.path.append(project_path_fa)

# 打印所有python解释器可以搜索到的所有路径
print(sys.path)


import traceback
from Freepatentsonline.databases.mongo_handler import Mongo_handler
from Freepatentsonline.extract.extract_async import Extract
from Freepatentsonline.settings import (CONFIG_DIR, RSYNC_DB_CONFIG_FILENAME,
                                        DB_CONFIG_FILENAME)
from Freepatentsonline.utils.path_file import get_config


# 数据库配置文件
RSYNC_DB_CONFIG = get_config(CONFIG_DIR, RSYNC_DB_CONFIG_FILENAME)


# 获取到 mongo 存储数据库配置信息
MONGO_LOCAL_CONFIG = RSYNC_DB_CONFIG["MONGO_LOCAL"]
MONGO_REMOTE_CONFIG = RSYNC_DB_CONFIG["MONGO_REMOTE"]

RSYNC_STATUS = 10


class Rsync:
    def __init__(self) -> None:

        self.extractor = Extract()
        self.mongo_local = Mongo_handler(MONGO_LOCAL_CONFIG)
        self.mongo_remote = Mongo_handler(MONGO_REMOTE_CONFIG)

        # loop = asyncio.get_event_loop()
        # loop.run_until_complete(self.run())

    def run(self):
        """"""
        collection_names = self.mongo_remote.db.list_collection_names()

        total_count = 0

        for collection_name in collection_names:
            print(f"当前collection :{collection_name}")
            remote_collection = self.mongo_remote.db[collection_name]
            local_collection = self.mongo_local.db[collection_name]

            # 查询数据
            while 1:
                result_cursor = remote_collection.find({"$or": [
                    {"rsync_status": {"$exists": False}},
                    {"rsync_status": 1},
                    {"rsync_status": 2},
                    {"rsync_status": 3},
                    {"rsync_status": 4},
                ]},
                ).limit(100)

                # 将数据插入到本地mogno
                data_li = [data for data in result_cursor]
                count = len(data_li)
                if count == 0:
                    break
                local_collection.insert_many(data_li)

                for data in data_li:

                    filter_data, _update_data = self.handle_data(data)
                    # 构建更新数据包
                    update_data = {'$set':  _update_data}

                    try:
                        # local_collection.insert_one(data)
                        remote_collection.update_one(filter_data, update_data)
                        total_count += 1
                        print(f"同步完成：{total_count}条...")
                    except:
                        print(traceback.format_exc())
                        filter_data["_id"] = str(filter_data["_id"])
                        error_info = {
                            "filter_data": filter_data,
                            "update_data": update_data,
                            "traceback_info": traceback.format_exc()
                        }
                        print(error_info)

                if count < 100:
                    break

            # break

    def handle_data(self, data):
        """
        解析查询出来的数据,并返回更新的条件数据和解析后的数据
        """

        filter_data = {"_id": data["_id"]}

        # 修改 extract_status ，该字段用于标识是否同步过数据
        update_data = {"rsync_status": RSYNC_STATUS}

        return filter_data, update_data


if __name__ == "__main__":
    r = Rsync()
    r.run()
